import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:studymanage/util/request.dart';
import 'package:url_launcher/url_launcher.dart';

import 'core/global.dart';
import 'home.dart';
import 'login/advertisement.dart';
import 'login/login.dart';

class UpdateVersion extends StatefulWidget {
  UpdateVersion({Key key,this.version,this.updateType,this.isNeedUpdate,this.downUrl}) : super(key: key);

  String version="";
  int updateType = 0;
  bool isNeedUpdate = false; //
  String downUrl ;

  @override
  State<StatefulWidget> createState() {
    return UpdateVersionState();
  }
}

class UpdateVersionState extends State<UpdateVersion> {
  double progress = 0;
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 668, allowFontScaling: true)..init(context);
    return Scaffold(
      body:  Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        color: Colors.black.withOpacity(0.5),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            CupertinoPopupSurface(
              isSurfacePainted: false,
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      width: ScreenUtil().setWidth(285),
                      height: ScreenUtil().setWidth(172),
                      decoration: BoxDecoration(
                        border: Border(
                          bottom: BorderSide(
                            width: ScreenUtil().setHeight(0.5),
                            color: Colors.white,
                          ),
                        ),
                        image: DecorationImage(
                          image: AssetImage('assets/images/login/dialog_bg.png'),
                          fit: BoxFit.fill,
                        ),
                      ),
                      padding: EdgeInsets.only(
                        left: ScreenUtil().setWidth(26),
                        top: ScreenUtil().setHeight(75),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text('发现新版本',
                            style: TextStyle(
                              fontFamily: 'PingFangSC-Medium',
                              fontSize: ScreenUtil().setSp(20),
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                              height: 1.4,
                            ),
                          ),
                          Text(widget.version,
                            style: TextStyle(
                              fontFamily: 'PingFangSC-Medium',
                              fontSize: ScreenUtil().setSp(20),
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                              height: 1.4,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: ScreenUtil().setWidth(284),
                      height: ScreenUtil().setHeight(90),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border(
                          top: BorderSide(
                            width: ScreenUtil().setHeight(0.5),
                            color: Colors.white,
                          ),
                        ),
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Text(
                            '现有新的版本更新',
                            style: TextStyle(
                              fontFamily: 'PingFangSC-Regular',
                              fontSize: ScreenUtil().setSp(16),
                              color: Color.fromRGBO(51, 51, 51, 1),
                              letterSpacing: ScreenUtil().setSp(1),
                              height: 1.47,
                            ),
                          ),
                          Text(
                            '请及时下载使用',
                            style: TextStyle(
                              fontFamily: 'PingFangSC-Regular',
                              fontSize: ScreenUtil().setSp(16),
                              color: Color.fromRGBO(51, 51, 51, 1),
                              letterSpacing: ScreenUtil().setSp(1),
                              height: 1.47,
                            ),
                          ),
                          Offstage(
                            offstage: progress == 0,
                            child: Text(
                              '下载进度${progress*100}%',
                              style: TextStyle(
                                fontFamily: 'PingFangSC-Regular',
                                fontSize: ScreenUtil().setSp(12),
                                color: Color.fromRGBO(51, 51, 51, 1),
                                letterSpacing: ScreenUtil().setSp(1),
                                height: 1.47,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Offstage(
                      offstage: widget.updateType == 0,
                      child: Container(
                        width: ScreenUtil().setWidth(284),
                        height: ScreenUtil().setHeight(44),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          border: Border(
                            top: BorderSide(
                              width: ScreenUtil().setHeight(0.5),
                              color: Color.fromRGBO(238, 238, 238, 1),
                            ),
                          ),
                        ),
                        child: FlatButton(
                          padding: EdgeInsets.all(0),
                          child: Text(
                            '取消更新',
                            style: TextStyle(
                              fontFamily: 'PingFangSC-Medium',
                              fontSize: ScreenUtil().setSp(18),
                              fontWeight: FontWeight.w600,
                              color: Color.fromRGBO(210, 180, 142, 1),
                              letterSpacing: ScreenUtil().setSp(1),
                              height: 1.47,
                            ),
                          ),
                          onPressed: () {
                            SharedPreferences.getInstance().then((share) {
                              share.setString("version", DateTime.now().year.toString() + DateTime.now().month.toString() + DateTime.now().day.toString());
                            });
                            if(Global.profile.token!=null){
                              Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => new Home(Global.profile.userTypeEnum ==1 ? Role.student : Role.teacher)), (Route<dynamic> route) => false);
                            }else{
                              Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => new Login(1)), (Route<dynamic> route) => false);
                            }
                          },
                        ),
                      ),
                    ),
                    Container(
                      width: ScreenUtil().setWidth(284),
                      height: ScreenUtil().setHeight(44),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        border: Border(
                          top: BorderSide(
                            width: ScreenUtil().setHeight(0.5),
                            color: Color.fromRGBO(238, 238, 238, 1),
                          ),
                        ),
                      ),
                      child: FlatButton(
                        padding: EdgeInsets.all(0),
                        child: Text(
                          '立即更新',
                          style: TextStyle(
                            fontFamily: 'PingFangSC-Medium',
                            fontSize: ScreenUtil().setSp(18),
                            fontWeight: FontWeight.w600,
                            color: Color.fromRGBO(210, 180, 142, 1),
                            letterSpacing: ScreenUtil().setSp(1),
                            height: 1.47,
                          ),
                        ),
                        onPressed: () =>_update(),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      )
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
  _update() async {

    if (Platform.isIOS) {
      final url = "https://itunes.apple.com/cn/app/1505924629"; // id 后面的数字换成自己的应用 id 就行了
      if (await launch(url)) {
        await launch(url, forceSafariVC: false);
      } else {
        throw 'Could not launch $url';
      }
    }
    if(Platform.isAndroid) {
      bool status = await Permission.storage.isGranted;
      if (!status) {
        Permission.storage.request();
      }
      Directory storageDir = await getExternalStorageDirectory();
      String storagePath = storageDir.path;
      File file = new File('$storagePath/tongaiv${widget.version}.apk');

      file.parent.create();
      if (!file.existsSync()) {
        file.createSync();
      }
      if(widget.downUrl!=null){
        Response response = await Dio().get(
            widget.downUrl,
            onReceiveProgress: showDownloadProgress,
            options: Options(
              responseType: ResponseType.bytes,
              followRedirects: false,
            ));
        file.writeAsBytesSync(response.data);
        OpenFile.open(file.path);
      }else{
        Request().toast("下载地址为空");
      }

      print('更新');
    }

  }

  void showDownloadProgress(num received, num total) {
    if (total != -1) {
      double progress = double.parse('${(received / total).toStringAsFixed(2)}');
      setState(() {
        progress = progress;
      });
    }
  }
}
